{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a2cf3fdb",
   "metadata": {},
   "source": [
    "# OnekeyStyle预览\n",
    "\n",
    "nc：大概你要做几个Signature（模型），估算就行！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ec79524",
   "metadata": {},
   "outputs": [],
   "source": [
    "nc = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fc2cb05",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from matplotlib.patches import Rectangle\n",
    "from matplotlib.colors import to_hex\n",
    "from onekey_algo.custom.components.comp1 import draw_roc, get_colors_from_config\n",
    "from sklearn.datasets import make_classification\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from onekey_algo import get_param_in_cwd\n",
    "\n",
    "def get_colors_from_colormap(n_colors, colormap_name='viridis'):\n",
    "    \"\"\"\n",
    "    从色彩映射中获取指定数量的颜色\n",
    "    \n",
    "    Args:\n",
    "        n_colors: 需要的颜色数量\n",
    "        colormap_name: 色彩映射名称，如 'viridis', 'plasma', 'rainbow', 'tab10'等\n",
    "    \n",
    "    Returns:\n",
    "        list: 颜色列表\n",
    "    \"\"\"\n",
    "    if colormap_name is None:\n",
    "        colors = get_colors_from_config(n_colors)\n",
    "    else:\n",
    "        colormap = plt.cm.get_cmap(colormap_name)\n",
    "        colors = [colormap(i) for i in np.linspace(0, 1, n_colors)]\n",
    "    return colors\n",
    "\n",
    "def show_color_palette(colors, title=\"颜色调色板\", figsize=(10, 2)):\n",
    "    \"\"\"\n",
    "    以色卡形式展示颜色列表\n",
    "    \n",
    "    Args:\n",
    "        colors: 颜色列表\n",
    "        title: 图表标题\n",
    "        figsize: 图表大小\n",
    "    \"\"\"\n",
    "    n_colors = len(colors)\n",
    "    \n",
    "    fig, ax = plt.subplots(1, 1, figsize=figsize)\n",
    "    \n",
    "    # 创建色卡\n",
    "    for i, color in enumerate(colors):\n",
    "        # 绘制颜色方块\n",
    "        rect = Rectangle((i, 0), 0.8, 0.8, facecolor=color, edgecolor='black', linewidth=1)\n",
    "        ax.add_patch(rect)\n",
    "        \n",
    "        # 添加颜色值文本\n",
    "        hex_color = to_hex(color)\n",
    "        ax.text(i + 0.4, -0.1, hex_color, ha='center', va='top', fontsize=8, rotation=45)\n",
    "        ax.text(i + 0.4, 0.9, f'#{i+1}', ha='center', va='bottom', fontsize=10, weight='bold')\n",
    "    \n",
    "    # 设置坐标轴\n",
    "    ax.set_xlim(0, n_colors)\n",
    "    ax.set_ylim(-0.3, 1)\n",
    "    ax.set_title(title, fontsize=14, pad=20)\n",
    "    ax.set_xticks([])\n",
    "    ax.set_yticks([])\n",
    "    \n",
    "    # 移除边框\n",
    "    for spine in ax.spines.values():\n",
    "        spine.set_visible(False)\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    return fig, ax\n",
    "\n",
    "def compare_colormaps(n_colors=8, colormap_names=None, figsize=(15, 80)):\n",
    "    \"\"\"\n",
    "    比较不同色彩映射的颜色\n",
    "    \n",
    "    Args:\n",
    "        n_colors: 每种色彩映射的颜色数量\n",
    "        colormap_names: 要比较的色彩映射名称列表\n",
    "        figsize: 图表大小\n",
    "    \"\"\"\n",
    "    if colormap_names is None:\n",
    "        colormap_names = [\n",
    "            'viridis', 'plasma', 'inferno', 'magma', 'cividis',\n",
    "            'tab10', 'tab20', 'Set1', 'Set2', 'Set3',\n",
    "            'Pastel1', 'Pastel2', 'Dark2', 'Accent',\n",
    "            'rainbow', 'jet', 'cool', 'hot', 'spring', 'summer'\n",
    "        ]\n",
    "    \n",
    "    n_maps = len(colormap_names)\n",
    "    cols = 4\n",
    "    rows = (n_maps + cols - 1) // cols\n",
    "    \n",
    "    fig, axes = plt.subplots(rows, cols, figsize=figsize)\n",
    "    axes = axes.flatten()\n",
    "    \n",
    "    for i, cmap_name in enumerate(colormap_names):\n",
    "        if i >= len(axes):\n",
    "            break\n",
    "            \n",
    "        try:\n",
    "            colors = get_colors_from_colormap(n_colors, cmap_name)\n",
    "            ax = axes[i]\n",
    "            \n",
    "            # 绘制色卡\n",
    "            for j, color in enumerate(colors):\n",
    "                rect = Rectangle((j, 0), 0.8, 0.8, facecolor=color, edgecolor='black', linewidth=0.5)\n",
    "                ax.add_patch(rect)\n",
    "            \n",
    "            # 设置子图\n",
    "            ax.set_xlim(0, n_colors)\n",
    "            ax.set_ylim(0, 1)\n",
    "            ax.set_title(cmap_name, fontsize=10, pad=5)\n",
    "            ax.set_xticks([])\n",
    "            ax.set_yticks([])\n",
    "            \n",
    "            # 移除边框\n",
    "            for spine in ax.spines.values():\n",
    "                spine.set_visible(False)\n",
    "                \n",
    "        except Exception as e:\n",
    "            print(f\"无法加载色彩映射 {cmap_name}: {e}\")\n",
    "            axes[i].set_visible(False)\n",
    "    \n",
    "    # 隐藏多余的子图\n",
    "    for j in range(i + 1, len(axes)):\n",
    "        axes[j].set_visible(False)\n",
    "    \n",
    "#     plt.suptitle(f'{n_colors} colors', fontsize=16, y=0.95)\n",
    "    plt.tight_layout()\n",
    "    return fig, axes\n",
    "\n",
    "def create_custom_palette(n_colors, colormap_name='viridis', show_palette=True):\n",
    "    \"\"\"\n",
    "    创建自定义调色板并展示\n",
    "    \n",
    "    Args:\n",
    "        n_colors: 颜色数量\n",
    "        colormap_name: 色彩映射名称\n",
    "        show_palette: 是否显示色卡\n",
    "    \n",
    "    Returns:\n",
    "        tuple: (颜色列表, 十六进制颜色列表)\n",
    "    \"\"\"\n",
    "    colors = get_colors_from_colormap(n_colors, colormap_name)\n",
    "    hex_colors = [to_hex(color) for color in colors]\n",
    "    \n",
    "    print(f\"调色板: {colormap_name}\")\n",
    "    print(f\"颜色数量: {n_colors}\")\n",
    "    print(\"颜色值:\")\n",
    "    for i, (color, hex_color) in enumerate(zip(colors, hex_colors)):\n",
    "        print(f\"  {i+1}: {hex_color} (RGB: {color[:3]})\")\n",
    "    \n",
    "    if show_palette:\n",
    "        show_color_palette(colors, f\"{colormap_name} 调色板 - {n_colors}种颜色\")\n",
    "    \n",
    "    return colors, hex_colors\n",
    "    \n",
    "# 示例使用\n",
    "colormap_names = [\n",
    "    'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap',\n",
    "    'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r',\n",
    "    'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r',\n",
    "    'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples',\n",
    "    'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r',\n",
    "    'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia',\n",
    "    'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot',\n",
    "    'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis',\n",
    "    'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'crest', 'crest_r', 'cubehelix',\n",
    "    'cubehelix_r', 'flag', 'flag_r', 'flare', 'flare_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r',\n",
    "    'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern',\n",
    "    'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r',\n",
    "    'hot', 'hot_r', 'hsv', 'hsv_r', 'icefire', 'icefire_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r',\n",
    "    'mako', 'mako_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r',\n",
    "    'prism', 'prism_r', 'rainbow', 'rainbow_r', 'rocket', 'rocket_r', 'seismic', 'seismic_r', 'spring', 'spring_r',\n",
    "    'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain',\n",
    "    'terrain_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'vlag',\n",
    "    'vlag_r', 'winter', 'winter_r'\n",
    "]\n",
    "\n",
    "print(\"\\n                                                          === 你自己设置的颜色 ===\")\n",
    "colors = get_colors_from_colormap(nc, None)\n",
    "show_color_palette(colors, f\"Yours settings for {nc} colors\")\n",
    "plt.show()\n",
    "\n",
    "print(\"\\n                                                          === 不同数量的颜色 ===\")\n",
    "fig, axes = plt.subplots(2, 2, figsize=(12, 8))\n",
    "\n",
    "if isinstance(get_param_in_cwd('display.colors'), str):\n",
    "    color_counts = [4, 8, 12, 16]\n",
    "    for i, count in enumerate(color_counts):\n",
    "        ax = axes[i//2, i%2]\n",
    "        colors = get_colors_from_colormap(count, get_param_in_cwd('display.colors'))\n",
    "\n",
    "        for j, color in enumerate(colors):\n",
    "            rect = Rectangle((j, 0), 0.8, 0.8, facecolor=color, edgecolor='black', linewidth=1)\n",
    "            ax.add_patch(rect)\n",
    "            ax.text(j + 0.4, -0.1, f'#{j+1}', ha='center', va='top', fontsize=8)\n",
    "\n",
    "        ax.set_xlim(0, count)\n",
    "        ax.set_ylim(-0.2, 1)\n",
    "        ax.set_title(f'{count} Colors', fontsize=12)\n",
    "        ax.set_xticks([])\n",
    "        ax.set_yticks([])\n",
    "\n",
    "    #     plt.suptitle('不同数量颜色的调色板', fontsize=16)\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "# 3. 比较不同色彩映射\n",
    "print(\"\\n                                                          === 比较不同色彩映射 ===\")\n",
    "compare_colormaps(n_colors=8, colormap_names=colormap_names)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee9413c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from matplotlib.patches import Rectangle\n",
    "from matplotlib.colors import to_hex\n",
    "from onekey_algo.custom.components.comp1 import draw_roc, get_colors_from_config\n",
    "from sklearn.datasets import make_classification\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from onekey_algo import get_param_in_cwd\n",
    "\n",
    "\n",
    "def generate_sample_data(num):\n",
    "    y_tests = []\n",
    "    y_scores = []\n",
    "    X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, \n",
    "                               n_redundant=5, n_classes=2, random_state=0)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "    for i in range(num):\n",
    "        # 生成分类数据\n",
    "        # 划分训练测试集\n",
    "\n",
    "        rf_model = RandomForestClassifier(n_estimators=random.randint(10, 100), random_state=i)\n",
    "        rf_model.fit(X_train, y_train)\n",
    "        rf_probs = rf_model.predict_proba(X_test)\n",
    "        y_tests.append(y_test)\n",
    "        y_scores.append(rf_probs)\n",
    "    \n",
    "    return y_tests, y_scores\n",
    "\n",
    "y_test, y_score = generate_sample_data(nc)\n",
    "labels = [f\"Model{i}\" for i in range(nc)]\n",
    "model_names = labels\n",
    "draw_roc(y_test, y_score, labels=labels)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "590f90c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from onekey_algo.custom.components.comp1 import draw_calibration\n",
    "draw_calibration(pred_scores=y_score, n_bins=5, y_test=y_test, model_names=labels)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f3f8caa",
   "metadata": {},
   "outputs": [],
   "source": [
    "from onekey_algo.custom.components.comp1 import plot_DCA\n",
    "plot_DCA([s[:, 1] for s in y_score], y_test[0], title=None, labels=labels, y_min=-0.15,)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "847368e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from onekey_algo.custom.components.delong import delong_roc_test\n",
    "from onekey_algo.custom.components.comp1 import draw_matrix\n",
    "\n",
    "delong = []\n",
    "delong_columns = []\n",
    "this_delong = []\n",
    "plt.figure(figsize=(8, 6))\n",
    "cm = np.zeros((len(model_names), len(model_names)))\n",
    "for i, mni in enumerate(model_names):\n",
    "    for j, mnj in enumerate(model_names):\n",
    "        if i <= j:\n",
    "            cm[i][j] = np.nan\n",
    "        else:\n",
    "            cm[i][j] = delong_roc_test(y_test[0], y_score[i][:,1], y_score[j][:,1])[0][0]\n",
    "cm = pd.DataFrame(cm[1:, :-1], index=model_names[1:], columns=model_names[:-1])\n",
    "draw_matrix(cm, annot=True, cmap='jet_r', cbar=True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e8f39e0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
